import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2025-02-12
 * Time: 14:34
 */
public class TestHeap {
    //存储数据
    public int[] elem;
    //存储有效数据的个数
    public int usedSize;

    public TestHeap(){
        elem = new int[10];
    }

    public void init(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    public void createHeap(){

        for (int parent  = (usedSize-1-1)/2; parent >= 0; parent--) {
            //从每棵子树开始向下调整
            siftDown(parent,usedSize);
        }
    }

    private void siftDown(int parent, int usedSize) {
        int child = 2 * parent + 1;
        //还没有调整完毕
        while (child < usedSize){
            if (elem[child] < elem[child+1]){
                child++;
            }
            //走到这里 child 下标一定是在左右孩子最大值的下标
            if (elem[child] > elem[parent]){
                swap(parent, child);
                parent = child;
                child = 2 * parent + 1;
            }else {
                break;
            }
        }
    }

    private void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    //插入数据
    //每次插入到当前堆的最后一个元素，然后向上调整
    public void offer(int val){
        if (isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = val;
        siftUp(usedSize);
        usedSize++;
    }

    private void siftUp(int child){
        int parent = (child-1)/2;
        while (parent >= 0){
            if (elem[child] > elem[parent]){
                swap(child,parent);
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }

    public boolean isFull(){
        return elem.length == usedSize;
    }

    //删除
    public int poll(){
        if (isEmpty()){
            //自己抛异常
            return -1;
        }
        int oldValue = elem[0];
        swap(0,usedSize-1);
        //调整0下标的树
        usedSize--;
        siftDown(0,usedSize);
        return oldValue;
    }

    public boolean isEmpty(){
        return usedSize == 0;
    }
    //堆排序：O（N*logN）
    //空间复杂度：O（1）
    public void heapSort(){
        int end = usedSize - 1;
        while (end > 0){
            swap(0,end);
            siftDown(0,end);
            end--;
        }
    }
}